#include "../Header/Precompiled.h"
#include "../Header/Vector2D.h"
#define PI D3DX_PI
#define EPSILON 0.0001

static void WrapFloat(float& val, float min, float max)
{
	ErrorIf(max < min, "ERROR: You fail at comparing two numbers. Max should > min!");
	if(val < min) val = max;
	else if (val > max) val = min;
}

const Vector2D Zero()
{
	return Vector2D(0.0f,0.0f);
}

// ---------------------------------------------------------------------------

Vector2D Vector2DFromAngle(float angle)
{
	return Vector2D(cos(angle),sin(angle));
}

// ---------------------------------------------------------------------------

Vector2D Vector2DNormalize(Vector2D vec0)
{
	if(vec0 == Zero()) return Zero();

	return vec0 / Vector2DLength(vec0);
}

// ---------------------------------------------------------------------------

Vector2D Vector2DProject(Vector2D vec0, Vector2D vec1)
{
	// projection of Vec0 on Vec1
	return Vector2DDotProduct(vec0,vec1) / Vector2DLength(vec1) * Vector2DNormalize(vec1);
}

// ---------------------------------------------------------------------------

float Vector2DDirection(Vector2D vec0)
{
	float result = atan(vec0.y/vec0.x);
	if(vec0.x < 0 && vec0.y < 0) result -= PI;
	else if(vec0.x < 0) result += PI;
	WrapFloat(result,-PI, PI);
	return result;
}

// ---------------------------------------------------------------------------

float	Vector2DLength(Vector2D vec0)
{
	return sqrt(Vector2DSquareLength(vec0));
}

// ---------------------------------------------------------------------------

float Vector2DSquareLength(Vector2D vec0)
{
	return pow(vec0.x,2) + pow(vec0.y,2);
}

// ---------------------------------------------------------------------------

float Vector2DDistance(Vector2D vec0, Vector2D vec1)
{
	return sqrt(Vector2DSquareDistance(vec0,vec1));
}

// ---------------------------------------------------------------------------

float Vector2DSquareDistance(Vector2D vec0,Vector2D vec1)
{
	return Vector2DSquareLength(vec0 - vec1);
}

// ---------------------------------------------------------------------------

float Vector2DDotProduct(Vector2D vec0, Vector2D vec1)
{
	return ((vec0.x * vec1.x) + (vec0.y * vec1.y));
}

// ---------------------------------------------------------------------------